package main

import (
	"fmt"
	"net"
	"strings"
)

func main() {

	listener, err := net.Listen("tcp", "127.0.0.1:6666")

	if err != nil {
		fmt.Println(" err = ", err)
		return
	}

	defer listener.Close()

	for {
		connection, conErr := listener.Accept()
		if conErr != nil {
			fmt.Println(" conErr = ", conErr)
			return
		}

		go handleConn(connection) // 开启协程处理连接数据
	}

}

func handleConn(conn net.Conn) {
	defer conn.Close()
	address := conn.RemoteAddr().String()
	fmt.Println(" s1 : address connection successful ! , ", address)

	buffer := make([]byte, 2048)
	for {
		dataIndex, dataErr := conn.Read(buffer)
		if dataErr != nil {
			fmt.Println(" se : connErr = ", dataErr)
			return
		}
		stringData := string(buffer[:dataIndex])
		fmt.Printf(" s2 : %s ==> getData : %s , len = %d \n ", address, stringData, len(stringData))

		// if "exit" == string(buffer[:(dataIndex-1)]) { // natcat-windows 测试
		// windows 客户端测试 cmd端多出两个字符 '\r\n' , git 客户端测试,只会多出 '\n'
		if "exit" == string(buffer[:(dataIndex-1)]) {

			fmt.Println(address, " has exited  ")
			return
		}

		conn.Write([]byte(strings.ToUpper(stringData))) // exit==> EXIT
	}

}
